<template>
    <el-container>
        <el-header>Header</el-header>

        <el-main>
            <div class="container">

                <span>线路:</span>
                <select class="s1" v-model="lot_code1" @change="updateLineId">
                    <option class="option" v-for="item in lotOptions" :key="item.text" :value="item.lot_code">{{
                        item.text
                        }}
                    </option>

                </select>
                <img src="../assets/箭头.png" @click="changePosition" alt="">
                <select class="s2" v-model="lot_code2" @change="updateLineId">
                    <option class="option" v-for="item in lotOptions" :key="item.text" :value="item.lot_code">{{
                        item.text
                        }}
                    </option>
                </select>
                <el-date-picker v-model="date" type="date" placeholder="请选择日期：" format="yyyy-MM-dd 星期ddd"
                    value-format="yyyy-MM-dd ">

                </el-date-picker>
                <button class="btn1" @click="Find">查询</button>

            </div>
            <div class="center">
                <input type="text" placeholder="请输入车牌号">
                <button class="btn1 " @click="Search">搜索</button>
                <button class="btn2" @click="pageValue(0)">排班({{ workLength }})</button>
                <button class="btn3" @click="pageValue(1)">已发车({{ depatchLength }})</button>
                <button class="btn3" @click="pageValue(2)">返程中({{ backLength }})</button>
                <ul v-el-table-infinite-scroll="LoadMore">
                    <el-table :data="tableData" height="350">
                        <el-table-column type="index" label="序号">
                        </el-table-column>
                        <el-table-column prop="driver_name" label="司机名称">
                        </el-table-column>
                        <el-table-column prop="car_number" label="车牌号">
                        </el-table-column>
                        <el-table-column prop="car_class_name" label="车型">
                        </el-table-column>
                        <el-table-column prop="Situation" label="派车情况" width="180">
                            <template slot-scope="scope">
                                {{ (scope.row.package_count) }}包{{ scope.row.empty_count }}空{{ scope.row.whole_car_count
                                }}货{{ scope.row.user_count }}拼
                            </template>
                        </el-table-column>
                        <el-table-column prop="ask_date" label="报班时间" :formatter="formatDate" width="180">
                        </el-table-column>
                        <el-table-column prop="driver_standby_seq" label="当日边次">
                        </el-table-column>
                        <el-table-column prop="status" label="智能调度状态">:formatter="statusReturn"
                            <template slot-scope="scope">
                                <span :style="statusReturn(scope.row.status).style">{{
                                    statusReturn(scope.row.status).text
                                }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="Operation" label="操作" width="180">
                            <template slot-scope="scope">
                                <el-button type="text" size="mini" @click="handleSupplement(scope.row)">补单</el-button>
                                <el-button type="text" size="mini" @click="handleDetails(scope.row)">详情</el-button>
                                <el-button type="text" size="mini" @click="handleDispatch(scope.row)">发车</el-button>
                            </template>

                        </el-table-column>

                    </el-table>
                </ul>


            </div>
            <div class="foot">
                <div class="foot-container">
                    <p style="margin-left: 20px;">实时线路数据</p>

                </div>
                <div class="content">
                    <div class="region">
                        <i class=" el-icon-tickets"></i>
                        <span>订单池</span>
                        <ul>
                            <li v-if="orderPool" class="style"> 拼车:{{ orderPool.order_type0_count }} </li>
                            <li v-if="orderPool" class="style">包车: {{ orderPool.order_type1_count }}</li>
                            <li v-if="orderPool" class="style"> 货件: {{ orderPool.order_type2_count }}</li>
                            <li v-if="orderPool" class="style"> 超时: {{ orderPool.expire_count }} </li>
                        </ul>
                    </div>

                    <div class="region2">
                        <img src="../assets/球体.png" alt="">
                        <span>当前运力</span>
                        <ul>
                            <li v-if="driverPool" class="style">5座: {{ driverPool.seats_5 }}</li>
                            <li v-if="driverPool" class="style">7座: {{ driverPool.seats_7 }}</li>
                            <li v-if="driverPool" class="style">返程中: {{ driverPool.return_count }}</li>
                        </ul>
                    </div>
                    <div class="region3">
                        <img src="../assets/数据2.png" alt="">
                        <span>实时总览数据</span>
                        <span class="sp1">统计截止时间:{{ this.date }}</span>
                        <div class="a1 clearflx">
                            <ul class="list1">
                                <li v-if="dispatchedData" class="style">总订单数(去重):
                                    {{ dispatchedData.all_true_count }}
                                </li>
                                <li v-if="dispatchedData" class="style">完成订单数:
                                    {{ dispatchedData.finished_count }}

                                </li>
                                <li v-if="dispatchedData" class="style">总边次:
                                    {{ dispatchedData.all_dispatched_count }}
                                </li>
                                <li v-if="dispatchedData" class="style">总载客数:
                                    {{ dispatchedData.finished_pcount }}

                                </li>
                            </ul>
                            <ul class="list2">
                                <li v-if="dispatchedData" class="style">撮合成功订单数:
                                    {{ dispatchedData.matched_order_count }}
                                </li>
                                <li v-if="dispatchedData" class="style">人工干预订单:
                                    {{ dispatchedData.man_order_count }}
                                </li>
                                <li v-if="dispatchedData" class="style">干预订单边次:
                                    {{ dispatchedData.man_dispatched_count }}

                                </li>
                            </ul>
                            <ul class="list3">
                                <li v-if="dispatchedData" class="style">用车数
                                    {{ dispatchedData.all_car_number }}

                                </li>
                                <li v-if="dispatchedData" class="style">消单率:
                                    {{ cancellationRate }}

                                </li>
                                <li v-if="dispatchedData" class="style">上座率:
                                    {{ occupancyRate }}
                                </li>
                            </ul>

                        </div>




                    </div>
                </div>

            </div>


        </el-main>


    </el-container>
</template>
<script>
import axios from 'axios'

export default {

    name: "Home",
    data() {
        return {
            lot_code1: "361000",
            lot_code2: "362000",

            date: "",
            noMoreData: false,//判断是否需要触发无限滚动
            originalTableData: [],//原始表格数据
            tableData: [],//搜索后表格数据
            orderPool: [],//订单池数据
            driverPool: [],//当前运力数据
            dispatchedData: [], //实时总览数据
            pageTypeValue: 0,
            limit: 10,
            pos: 0,
            workLength: 0,//排班数据的长度
            depatchLength: 0,
            backLength: 0,
            lotOptions: [
                {
                    text: '厦门市|城际|XMCJ',
                    lot_code: '361000',
                    lot_name: '厦门市'
                },
                {
                    text: '泉州市|城际|QZCJ',
                    lot_code: '362000',
                    lot_name: '泉州市'
                },
                {
                    text: '安溪县|城际|AXCJ',
                    lot_code: '362400',
                    lot_name: '安溪县'
                },
                {
                    text: '漳州市|城际|ZZCJ',
                    lot_code: '363000',
                    lot_name: '漳州市'
                },
            ]

        }
    },
    created() {
        this.updateLineId();//lineid初始化
    },
    activated() {
        this.updateLineId();//确保传入的数据是最新的
        this.Find();
    },
    computed: {
        cancellationRate() {
            if (this.dispatchedData && this.dispatchedData.all_true_count > 0) {
                return (this.dispatchedData.cancel_true_count / this.dispatchedData.all_true_count * 100).toFixed(2) + '%';
            }
            return '0%';
        },
        occupancyRate() {
            if (this.dispatchedData && this.dispatchedData.all_true_count > 0) {
                return (this.dispatchedData.finished_pcount / this.dispatchedData.all_pcount * 100).toFixed(2) + '%';
            }
            return '0%'
        },

    },
    methods: {
        updateDayAt() {
            // 确保 this.date 是一个有效的日期字符串
            if (this.date) {
                // 更新 day_at 的值为 this.date
                this.day_at = this.date;
            } else {
                // 如果 this.date 不是一个有效的日期，可以设置默认值或者清空 day_at
                this.day_at = ''; // 或者设置一个默认日期
            }
        },
        Find() {
            this.updateDayAt();// 在调用 Find 方法之前，确保 day_at 已经被更新
            axios.post('/pub/ai/driver_page_list', {
                line_id: this.lineId,
                oc_code: ["10596", "10592"],
                page_type: this.pageTypeValue,
                pos: 0,
                limit: this.limit,
            }, {
                headers: {
                    "user-token": "12306070809_" + "8a4a3c08a3f4425587f1ca8228c2bc69",
                },
            })
                .then(response => {
                    if (response.data.status === 0) {
                        this.tableData = this.originalTableData = response.data.result.map((item, index) => {
                            item.serialNumber = index + 1//初始化serialNumber为0，根据index累加
                            return item//序号列的方法
                        })
                        console.log(response); // 在控制台输出响应数据
                        //console.log(this.lineId);
                        this.workLength = this.tableData.length
                        if (response.data.result.length < 10) {
                            this.noMoreData = true;
                        } else {
                            this.noMoreData = false
                        }
                    } else {
                        // 如果状态码不是0，弹出错误信息
                        this.$message(response.data.status + '，错误信息：' + response.data.message, '错误', {
                            type: 'error'
                        });
                    }


                })
                .catch(err => {
                    this.error = "请求异常"; // 记录错误信息
                    console.error(err); // 在控制台输出错误信息
                });
            axios.post('/pub/ai/order_view', {
                "day_at": this.date,
                "line_id": this.lineId
            }, {
                headers: {
                    "user-token": "12306070809_" + "8a4a3c08a3f4425587f1ca8228c2bc69",
                },
            })
                .then(response1 => {
                    if (response1.data.status == 0) {


                        this.orderPool = response1.data.result.info
                        console.log(response1.data);
                    } else {
                        this.$message(response.data.status + '，错误信息：' + response.data.message, '错误', {
                            type: 'error'
                        });
                    }

                })
                .catch(err => {
                    console.error(err);
                })
            axios.post('/pub/ai/driver_view', {
                "day_at": this.date,
                "line_id": this.lineId
            }, {
                headers: {
                    "user-token": "12306070809_" + "8a4a3c08a3f4425587f1ca8228c2bc69",
                },

            })
                .then(response2 => {
                    if (response2.data.status == 0) {


                        this.driverPool = response2.data.result.info
                    } else {
                        this.$message(response.data.status + '，错误信息：' + response.data.message, '错误', {
                            type: 'error'
                        });
                    }
                })
                .catch(err => {
                    console.error(err);
                })
            axios.post('/pub/ai/dispatched_view', {
                "day_at": this.date,
                "line_id": this.lineId
            }, {
                headers: {
                    "user-token": "12306070809_" + "8a4a3c08a3f4425587f1ca8228c2bc69",
                },

            })
                .then(response3 => {
                    if (response3.data.status == 0) {
                        this.dispatchedData = response3.data.result.info
                    } else {
                        this.$message(response3.data.status + '，错误信息：' + response3.data.message, '错误', {
                            type: 'error'
                        });
                    }

                })
                .catch(err => {
                    console.error(err);
                })

        },
        orderWork() {//排班方法

            this.tableData.length = this.workLength
        },
        handleSupplement(row) {
            const carNumber = row.car_number;
            const lineId = this.lineId;
            const driverId = row.driver_id;
            const dispatchedId = row.dispatched_id;
            console.log(carNumber, lineId, dispatchedId, driverId);


            this.$router.push({
                path: '/supplement',
                query: {
                    car_number: carNumber, // 将车牌号作为查询参数传递
                    line_id: this.lineId,
                    driver_id: driverId,
                    dispatched_id: dispatchedId,


                }
            });
        },
        handleDetails(row) {

            const carNumber = row.car_number;
            const lineId = this.lineId;
            const driverId = row.driver_id;
            const dispatchedId = row.dispatched_id;

            console.log(carNumber);

            this.$router.push({
                path: '/xiangqing',
                query: {
                    car_number: carNumber, // 将车牌号作为查询参数传递
                    line_id: this.lineId,
                    driver_id: driverId,
                    dispatched_id: dispatchedId,
                }
            });

        },
        handleDispatch() {
            // console.log("发车");
        },
        formatDate(row, column, ask_date) {
            const date = new Date(ask_date);
            const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以需要+1
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');

            // 使用所需的格式构建日期字符串
            return `${month}-${day} ${hours}:${minutes}`;
        },
        statusReturn(status) {
            const color = status === 0 ? '#2CBB82' : 'red';
            return {
                style: `color: ${color};`, // 返回内联样式
                text: status === 0 ? '正常' : '异常' // 返回状态文本
            };
        },
        Search() {
            let plateNumber = document.querySelector('.center input[type="text"]').value.trim(); // 获取输入的车牌号

            if (plateNumber) {
                const foundItem = this.originalTableData.filter(item => item.car_number === plateNumber);
                if (foundItem.length > 0) {
                    this.tableData = foundItem; // 只返回找到的车牌号对应的数据
                } else {
                    this.originalTableData = this.tableData
                }
            }

        },
        updateLineId() {
            if (this.lot_code1 && this.lot_code2) {
                this.lineId = `${this.lot_code1}_to_${this.lot_code2}`
            }
        },
        changePosition() {
            let temp = this.lot_code1;
            this.lot_code1 = this.lot_code2;
            this.lot_code2 = temp;
            this.updateLineId();
            this.pos = 0;//重置pos值
        },
        found() {
            axios.post('/pub/ai/driver_page_list', {
                line_id: this.lineId,
                oc_code: ["10596", "10592"],
                page_type: this.pageTypeValue,
                pos: this.pos,
                limit: this.limit,
            }, {
                headers: {
                    "user-token": "12306070809_" + "8a4a3c08a3f4425587f1ca8228c2bc69",
                },
            })
                .then(response4 => {
                    if (response4.data.status == 0) {


                        if (response4.data && response4.data.result) {
                            this.tableData = response4.data.result;
                        } else {
                            this.tableData = [];
                        }
                    } else {
                        this.$message(response4.data.status + '，错误信息：' + response4.data.message, '错误', {
                            type: 'error'
                        });
                    }

                })
                .catch(err => {
                    this.error = "请求异常"; // 记录错误信息
                    console.error(err); // 在控制台输出错误信息
                });

        },
        pageValue(page_type) {
            this.pageTypeValue = page_type//更新page_type的值
            this.pageType(this.pageTypeValue)
            //console.log(page_type);
            this.pos = 0;// 重置pos值，按钮切换时有数据
            this.found();

        },
        pageType(page_type) {
            switch (page_type) {
                case 0:
                    //排班
                    this.orderWork();


                    break;
                case 1:
                    this.depatch();


                    break;
                case 2:

                    this.tracking();

                    break;
                default:
                    console.error('Invalid page type');
            }
            return (page_type)
        },
        depatch() {
            this.tableData.length = this.depatchLength



        },
        tracking() {
            this.tableData.length = this.backLength



        },
        LoadMore() {
            if (this.noMoreData) {
                console.log(this.noMoreData);
                return
            }
            this.pos += this.limit;
            axios.post('/pub/ai/driver_page_list', {
                line_id: this.lineId,
                oc_code: ["10596", "10592"],
                page_type: this.pageTypeValue,
                pos: this.pos,
                limit: this.limit
            }, {
                headers: {
                    "user-token": "12306070809_" + "8a4a3c08a3f4425587f1ca8228c2bc69"
                }
            })
                .then(response5 => {
                    if (response5.data.status == 0) {


                        if (response5.data && response5.data.result) {
                            // 添加将新数据插入到原数据中的逻辑
                            this.originalTableData = this.originalTableData.concat(response5.data.result);
                            // 更新 tableData
                            this.tableData = this.originalTableData;
                            // 重新计算 workLength
                            this.workLength = this.tableData.length;

                            // 判断返回的数据长度是否小于 limit，如果是，则设置 noMoreData 为 true
                            if (response5.data.result.length < 10) {
                                this.noMoreData = true;
                            }
                        }
                    } else {
                        this.$message(response.data.status + '，错误信息：' + response.data.message, '错误', {
                            type: 'error'
                        });
                    }
                })
                .catch(err => {
                    this.error = "请求异常";
                    console.error(err);
                });
        },
    },
}
</script>
<style scoped>
.container {
    height: 72px;
}

span {
    margin-right: 12px;
    font-weight: bold
}

.option {
    font-weight: 400;

    color: #303133;
    line-height: 24px;
    text-align: left;
    font-style: normal;
}

img {
    margin-left: 20px
}

.s1,
.s2,
input {
    width: 224px;
    height: 40px;
    background: #FFFFFF;
    border-radius: 4px;
    border: 1px solid #D8DCE6;
    margin-left: 16px;
}

.el-date-editor {
    margin-left: 64px;
}

.center {
    width: 100%;
    height: 451px;
}

.btn1 {
    width: 64px;
    height: 40px;
    background: #1989FA;
    border-radius: 4px;
    color: white;
    margin-left: 20px;
}

.btn3 {
    width: 115px;
    height: 36px;
    border: 1px solid #DCDFE6;

}

.btn3:active {
    background-color: #1989FA;
}

.btn2 {
    width: 104px;
    height: 36px;
    margin-left: 20px;
    border: 1px solid #DCDFE6;
    background: #A3D0FD;
    border: #A3D0FD;
    color: #1989FA;
}

.btn2:active {
    background: #DCDFE6;
    color: black;
}

.el-table {
    margin-top: 21px;
    border: 1px solid;
}

.foot {
    height: 263px;


}

.foot-container {
    height: 54px;
    border: 1px solid #EBEEF5;
}

.el-icon-tickets:before {

    font-size: 20px;
    color: #588CFC;
    border-radius: 2px;


}

ul,
li {
    text-decoration: none;
    list-style: none;

}

li {
    color: #666666;
}

.content {
    display: flex;
    margin-top: 40px;

}

.region,
.region2,
.region3 {
    margin-right: 60px;
}

.region li,
.region2 li {
    width: 100px;
}

.region3 li {
    width: 120px;
}

.sp1 {
    color: #909399;
}

.region3 ul {
    float: left;
}

.clearflx::after {
    /* clearflx为清除浮动的样式*/
    content: '';
    display: block;
    clear: both;
}

.content span {
    margin-left: 12px
}

.region3 li {
    padding-top: 10px;
}

.style {
    color: #000;
    padding-top: 10px;
}
</style>